package
{
	import events.MultipartURLLoaderEvent;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.StatusEvent;
	import flash.events.TimerEvent;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.net.LocalConnection;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import template1.MainScreen;
	import template1.ResultScreen;
	import template1.VideoScreen;
	
	import template2.MainScreenFrench;
	import template2.ResultScreenFrench;
	import template2.VideoScreenFrench;
	
	import template3.MainScreenRussian;
	import template3.ResultScreenRussian;
	import template3.VideoScreenRussian;
	
	import template4.MainScreenSpanish;
	import template4.ResultScreenSpanish;
	import template4.VideoScreenSpanish;
	
	[SWF(width="600", height="480", backgroundColor="#ffffff", frameRate="30")]
	public class VigureMatching extends Sprite
	{
		private var connection:LocalConnection;
		private var sendConn:LocalConnection = new LocalConnection();
		private var flexConnectionID:String;
		private var swfConnectionID:String;
		private var myJSONdata:Object;
		private var assArray:Array = new Array();
		private var modelArray:Array = new Array();
		private var iconUrl:String;
		private var recordId:Number;
		private var success_icon:String
		private var vigId:String;
		private var gameId:String;
		private var tempId:String;
		private var content1:String;
		private var content2:String;
		private var catchoomItemId:String;
		private var itemIdArray:Array;
		private var loader:URLLoader;
		private var request:URLRequest;
		private var jsonContent:URLLoader;
		private var errorMode:Number;
		
		private var mainScreenEnglish:MainScreen;
		private var mainScreenFrench:MainScreenFrench;
		private var mainScreenRussian:MainScreenRussian;
		private var mainScreenSpanish:MainScreenSpanish;
		
		private var videoScreenEnglish:VideoScreen;
		private var videoScreenFrench:VideoScreenFrench;
		private var videoScreenRussian:VideoScreenRussian;
		private var videoScreenSpanish:VideoScreenSpanish;
		
		[Embed(source = "Ubuntu-R.ttf",
			fontName = "Ubuntu",
			fontFamily = "Ubuntu",
			fontWeight = "normal",
			fontStyle = "normal",
			mimeType = "application/x-font",
			advancedAntiAliasing="true",
			embedAsCFF="false")]
		private var myEmbeddedFont:Class;
		public function VigureMatching()
		{
			sendConn.allowDomain("*");
			
			connection = new LocalConnection();
			connection.client = this;
			connection.allowDomain("*");
			
			this.addEventListener(Event.ADDED_TO_STAGE, addToStageHandler)
			//setGameData( "Unlock a Mushroom by holding up this Campbell's Soup to your webcam.", "Hold up any of these to your webcam, hold it close and steady.", "1", "28", "1");		
			//setGameData("TEMPLATE TEXT. TEMPLATE TEXT. TEMPLATE TEXT. TEMPLATE TEXT.  TEMPLATE TEXT.", "HOLD UP A REAL WORLD ITEM TO YOUR WEBCAM TO UNLOCK VIRTUAL GOODNESS.", "92", "23", "1");
		}
		private function addToStageHandler(e:Event):void
		{
			try
			{
				if (this.loaderInfo.parameters.hasOwnProperty("flexConnectionID"))
					flexConnectionID = this.loaderInfo.parameters.flexConnectionID;
				if (this.loaderInfo.parameters.hasOwnProperty("swfConnectionID"))	
				{
					swfConnectionID = this.loaderInfo.parameters.swfConnectionID;
					connection.connect(swfConnectionID);
				}
				
			}catch(e:Error) {}
		}
		public function setGameData(str1:String, str2:String, vigId:String, gameId:String, tempId:String):void
		{
			if(vigId !=null)
				this.vigId = vigId;  
			if(gameId !=null)
				this.gameId = gameId; 
			if(tempId !=null)
				this.tempId = tempId;
			if(str1 !=null)
				this.content1 = str1;
			if(str2 !=null)
				this.content2 = str2;
			
			loader = new URLLoader()
			var url:String = "http://www.vigure.com/restApi/rest/task/validateGame/vigId/"+vigId+"/gameId/" +gameId;
			request = new URLRequest(url);
			
			loader.load(request);
			loader.addEventListener(Event.COMPLETE, jsonLoaded);
			loader.addEventListener(IOErrorEvent.IO_ERROR, jsonLoadError);
		}
		private function jsonLoaded(event:Event):void
		{
			jsonContent = URLLoader(event.target);      
			myJSONdata = JSON.parse(jsonContent.data);  
			errorMode = myJSONdata.ErrorMode as Number;
			
			if (errorMode == 1)
			{
				showErrorMessage(myJSONdata.ErrorMessage as String);
			}
			else
			{
				assArray = myJSONdata.ass as Array;
				modelArray = myJSONdata.model as Array;
				iconUrl = myJSONdata.icon as String;
				success_icon = myJSONdata.success_icon as String;
				this.recordId = myJSONdata.recordId as Number;
				catchoomItemId = myJSONdata.catchoomItemId as String;
				itemIdArray=catchoomItemId.split(",");
				
				if((Number(tempId) == 0) || (Number(tempId) > 4))
				{
					var ob:Object = new Object();
					ob.recordId = this.recordId;
					ob.gameId = this.gameId;
					ob.vigId = this.vigId;
					if(assArray.length>0)
						ob.assArray = this.assArray;
					initCamera(402, 200, 193, 88)
				}
				else
				{
					if (tempId == "1") //for English
					{
						mainScreenEnglish = new MainScreen();
						loadMainScreen(mainScreenEnglish);
					}
					else if (tempId == "2") //for French
					{
						mainScreenFrench = new MainScreenFrench();
						loadMainScreen(mainScreenFrench);
					}
					else if (tempId == "3") //for Russian
					{
						mainScreenRussian = new MainScreenRussian();
						loadMainScreen(mainScreenRussian);
					}
					else if (tempId == "4") //for Spanish
					{
						mainScreenSpanish = new MainScreenSpanish();
						loadMainScreen(mainScreenSpanish);
					}
				}		
			}
		}
		private function jsonLoadError(event:IOErrorEvent):void
		{
			//vigId = "92";
			//gameId = "23";
			//recordId = "184";
			
		}
		
		private function showErrorMessage(errorMessage:String):void
		{            
			var txt:TextField = new TextField();
			addChild(txt);
			txt.multiline = true
			txt.wordWrap = true;
			txt.embedFonts = true;
			txt.defaultTextFormat = new TextFormat("Ubuntu" ,14,null,null,null,null,null,null, "center");
			txt.text = errorMessage;
			txt.width = 380;
			txt.height = txt.textHeight+5;
			txt.x = (800 - txt.width) / 2
			txt.y = (600 - txt.textHeight) / 2;
			timer1.addEventListener(TimerEvent.TIMER, handleTimerStart)
			timer1.start();
		}
		private function handleTimerStart(e:TimerEvent):void
		{
			timer1.stop();
			sendConn.send(flexConnectionID, 'failure', 1 ,myJSONdata.ErrorMessage as String)
		}
		private function loadMainScreen(mainScreen:MovieClip):void
		{
			addChild(mainScreen);
			if(iconUrl !=null)
				mainScreen.iconImageUrl = iconUrl;
			if(modelArray[0] !=null)
				mainScreen.imageUrl = modelArray[0];
			if(content1 !=null)
				mainScreen.contentText = content1;
			mainScreen.addEventListener(MainScreen.OK, handleClick);
			mainScreen.addEventListener(MainScreen.CANCEL, handleCancel);
		}
		
		private function handleClick(e:Event):void
		{
			if (tempId == "1")
			{	
				removeChild(mainScreenEnglish);
				videoScreenEnglish = new VideoScreen();
				loadVideoScreen(videoScreenEnglish);
			}
			else if (tempId == "2")
			{
				removeChild(mainScreenFrench);
				videoScreenFrench = new VideoScreenFrench();
				loadVideoScreen(videoScreenFrench);
			}
			else if (tempId == "3")
			{
				removeChild(mainScreenRussian);
				videoScreenRussian = new VideoScreenRussian();
				loadVideoScreen(videoScreenRussian);
			}
			else if (tempId == "4")
			{
				removeChild(mainScreenSpanish);
				videoScreenSpanish = new VideoScreenSpanish();
				loadVideoScreen(videoScreenSpanish);
			}
			
		}
		private function handleCancel(e:Event):void
		{
			var url:String = "http://www.vigure.com/restApi/rest?task=cancelGame&vigId=" + vigId + "&gameId=" + gameId + "&recordId=" + recordId + "&cancelStep=1";
			var urlRequest:URLRequest = new URLRequest(url);
			urlRequest.method = URLRequestMethod.POST;
			
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			urlLoader.addEventListener(Event.COMPLETE, loadComplete);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			urlLoader.load(urlRequest);
			
			sendConn.send(flexConnectionID, 'failure', 2 ,'errorMessage')	
		}
		private function loadVideoScreen(videoScreen:MovieClip):void
		{
			var ob:Object = new Object();
			ob.recordId = this.recordId;
			ob.gameId = this.gameId;
			ob.vigId = this.vigId;
			if(assArray.length>0)
				ob.assArray = this.assArray;
			
			addChild(videoScreen);
			videoScreen.addEventListener(VideoScreen.CANCEL, handleVideoScreenCancel);
			//if((content2 != null)&&(tempId !="1"))
			if((content2 != null))
			{
				videoScreen.contentText = content2;
			}
			if (modelArray.length == 1)
			{
				videoScreen.image1Url = "";
				videoScreen.image2Url = "";
				videoScreen.image3Url = "";
			}
			if (modelArray.length == 2)
			{
				if(modelArray[1] != null)	
					videoScreen.image2Url = modelArray[1];
			}
			else if (modelArray.length == 3)
			{
				if(modelArray[1] != null)	
					videoScreen.image1Url = modelArray[1];
				if(modelArray[2] != null)	
					videoScreen.image2Url = modelArray[2];
			}
			else
			{
				if(modelArray[1] != null)	
					videoScreen.image1Url = modelArray[1];
				if(modelArray[2] != null)	
					videoScreen.image2Url = modelArray[2];
				if(modelArray[3] != null)	
					videoScreen.image3Url = modelArray[3];
			}			
					
			initCamera(videoScreen.videoWidth, videoScreen.videoHeight, videoScreen.videoX,videoScreen.videoY)
		}
		private var video:Video;
		public var screenshot:BitmapData;
		private var timer:Timer = new Timer(100);
		protected function initCamera(width:int, height:int, xx:int, yy:int):void
		{
			var streamW:int = width;
			var streamH:int = height;
			var streamFPS:int = 30;
			var downScaleRatio:Number = 1;
			var workW:int = streamW * downScaleRatio;
			var workH:int = streamH * downScaleRatio;
			var viewWidth:int = width;
			var viewHeight:int = height;
			
			try
			{
				var bandwidth:int = 0; // Maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second.
				var quality:int = 100; // This value is 0-100 with 1 being the lowest quality. 
				var camera:Camera = flash.media.Camera.getCamera();
				if (camera != null)
				{
					camera.setQuality(bandwidth, quality);
					camera.setMode(streamW, streamH, streamFPS, false);
					camera.addEventListener(StatusEvent.STATUS, handleCameraStatus);
					video = new Video(viewWidth, viewHeight);
					video.x=xx;
					video.y=yy;
					video.attachCamera(camera);
					this.addChild(video);
					if(!camera.muted)
					{
						timer.addEventListener(TimerEvent.TIMER, handleTimerStartUp)
						timer.start();
					}
				}
				else
				{
					//dispatchEvent(new Event(CAMERA_NOT_SUPPORTED));
					handleCameraIssue();
				}
			}
			catch (e:Error)
			{
				//trace("CAMERA_NOT_SUPPORTED")
			}
		}
		private var byteArray:ByteArray;
		private var multiPartLoader:MultipartURLLoader;
		private var myEncoder:JPEGAsyncEncoder;
		private function handleTimerStartUp(e:TimerEvent):void
		{
			//txt.appendText("handleTimerStartUp");
			timer.stop();
			screenshot = new BitmapData(video.width, video.height);
			screenshot.draw(video);
			try
			{
				myEncoder= new JPEGAsyncEncoder(75);
				myEncoder.addEventListener(JPEGAsyncCompleteEvent.JPEGASYNC_COMPLETE, jpegAsycComplete);
				myEncoder.PixelsPerIteration=2000;
				myEncoder.encode(screenshot);
				
			}
			catch (e:Error)
			{
				trace("error -- "+e.toString()+"---");
			}
			
		}
		private function jpegAsycComplete(e:JPEGAsyncCompleteEvent):void
		{
			multiPartLoader=new MultipartURLLoader();
			var fileName:String=new Date().valueOf()+".jpg";
			multiPartLoader.addEventListener(Event.COMPLETE,handleMultipartLoaderComplete);
			multiPartLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS,handleHtttpStatus);
			multiPartLoader.addEventListener(IOErrorEvent.IO_ERROR, handleMultiPartError);
			multiPartLoader.addEventListener(MultipartURLLoaderEvent.DATA_PREPARE_COMPLETE, handleDataPrepareComplete)
			multiPartLoader.addFile(myEncoder.ImageData, fileName, "image");
			multiPartLoader.load("https://r.catchoom.com/v0/search?token=ed73baa155ec4421", true);
			trace("initCamera - image loaded")
		}
		
		private function handleDataPrepareComplete(event:MultipartURLLoaderEvent):void
		{
			trace("-------------------handleDataPrepareComplete-------------- ");
			multiPartLoader.startLoad();
		}
		private function handleMultipartLoaderComplete(event:Event):void
		{
			trace("-------------------handleMultipartLoaderComplete-------------- ");
			var jsonContentLoader:MultipartURLLoader = MultipartURLLoader(event.target);
			var data:Object = JSON.parse(jsonContentLoader.getData());
			if(data[0] != null)
			{	
				if(data[0].hasOwnProperty("item_id"))
				{
					trace("item_id "+data[0].item_id.toString());
					for(var i:uint=0;i<itemIdArray.length;i++)
					{
						//trace("i "+i+" item id "+itemIdArray[i]);
						if(data[0].item_id.toString()==itemIdArray[i])
						{
							trace("------------------matched------------------------");
							video.attachCamera(null);
							var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
							var url:String = "http://www.vigure.com/restApi/rest/task/successGame/vigId/"+vigId+"/gameId/"+gameId+"/recordId/" + recordId;
							var saveJPG:URLRequest = new URLRequest(url);
							
							saveJPG.requestHeaders.push(header);
							saveJPG.method = URLRequestMethod.POST;
							saveJPG.data = myEncoder.ImageData;
							
							var urlLoader:URLLoader = new URLLoader();
							urlLoader.addEventListener(Event.COMPLETE, loadComplete);
							urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
							urlLoader.load(saveJPG);
							handleSuccess();
							timer.stop();
						}
						else
							timer.start();
					}
				}
				else
					trace("item_id blanck");
			}
			else
			{
				trace("data[0] null ");
				timer.start();
			}
				
//			trace("image_id "+data[0].image_id.toString());
//			trace("metadata name  "+data[0].metadata.name.toString());
//			trace("metadata url "+data[0].metadata.url.toString());
//			trace("metadata thumbnail "+data[0].metadata.thumbnail.toString());
		}
		private function handleMultiPartError(event:IOErrorEvent):void
		{
			trace("Error -> "+event.toString());
		}
		private function handleHtttpStatus(event:HTTPStatusEvent):void
		{
			trace("Status -> "+event.toString());
		}
		private function handleCameraStatus(e:StatusEvent):void
		{
			switch (e.code) 
			{	 
				case "Camera.Muted": 
				{
					trace("User clicked Deny."); 
					var url:String = "http://www.vigure.com/restApi/rest/task/cancelGame?vigId="+ vigId + "&gameId=" + gameId + "&recordId=" + recordId + "&cancelStep=2";
					var urlRequest:URLRequest = new URLRequest(url);
					urlRequest.method = URLRequestMethod.POST;
					
					var urlLoader:URLLoader = new URLLoader();
					urlLoader.addEventListener(Event.COMPLETE, onCameraMute);
					urlLoader.load(urlRequest);
					
					handleDenyClick();
				}
					break; 
				case "Camera.Unmuted": 
				{
					trace("User clicked Accept.");
					timer.addEventListener(TimerEvent.TIMER, handleTimerStartUp)
					timer.start();
				}
					break; 
			}		 
			
		}
		private function onCameraMute(e:Event):void
		{
			
		}
		private function handleDenyClick():void
		{
			sendConn.send(flexConnectionID, 'failure', 3 ,'ErrorMessage')
		}
		private function handleVideoScreenCancel(e:Event):void
		{
			var url:String = "http://www.vigure.com/restApi/rest?task=cancelGame&vigId="+ vigId + "&gameId=" + gameId + "&recordId=" + recordId + "&cancelStep=3";
			var urlRequest:URLRequest = new URLRequest(url);
			urlRequest.method = URLRequestMethod.POST;
			
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, loadComplete);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			urlLoader.load(urlRequest);
			
			sendConn.send(flexConnectionID, 'failure', 4 ,'errorMessage')
		}
		private function loadComplete(e:Event):void
		{  
			trace("url loaded");
		}
		private function onLoadError(e:IOErrorEvent):void
		{
			trace("loading error on cancel   " + e.toString());
		}
		private var timer1:Timer=new Timer(5000);
		private function handleSuccess():void
		{
			timer1.addEventListener(TimerEvent.TIMER, handleTimer)
			timer1.start();
			
			if (tempId == "1")
			{
				removeChild(videoScreenEnglish);
				var resultSrceenEnglish:ResultScreen = new ResultScreen()
				loadResultScreen(resultSrceenEnglish);
			}
			else if (tempId == "2")
			{
				removeChild(videoScreenFrench);
				var resultSrceenFrench:ResultScreenFrench = new ResultScreenFrench()
				loadResultScreen(resultSrceenFrench);
			}
			else if (tempId == "3")
			{
				removeChild(videoScreenRussian);
				var resultSrceenRussian:ResultScreenRussian = new ResultScreenRussian()
				loadResultScreen(resultSrceenRussian);
			}
			else if (tempId == "4")
			{
				removeChild(videoScreenSpanish);
				var resultSrceenSpanish:ResultScreenSpanish = new ResultScreenSpanish()
				loadResultScreen(resultSrceenSpanish);
			}
			else
			{
				var screenShot:Image = new Image();
				screenShot.x = 193;
				screenShot.y = 88;
				screenShot.dimension(402, 200);
				this.addChild(screenShot);
				screenShot.bitmap = new Bitmap(screenshot);
			}
		}
		private function loadResultScreen(resultScreen:MovieClip):void
		{
			addChild(resultScreen);
			resultScreen.screenShotBitmap=new Bitmap(screenshot);
			if(success_icon != null)
			{
				resultScreen.imageUrl = success_icon;
			}
			
		}
		private function handleTimer(e:TimerEvent):void
		{
			timer1.stop();
			sendConn.send(flexConnectionID, 'success');
		}
		private function handleCameraIssue():void
		{
			var txt:TextField = new TextField();
			
			if (tempId == "1")
			{
				videoScreenEnglish.addChild(txt);
				txt.multiline = true
				txt.wordWrap = true;
				txt.embedFonts = true;
				txt.defaultTextFormat = new TextFormat("Ubuntu" ,14,null,null,null,null,null,null, "center");
				txt.text = "No Camera Detected.";
				txt.width = 380;
				txt.height = txt.textHeight + 5;
				txt.x = (800 - txt.width) / 2
				txt.y = (300 - txt.textHeight) / 2;
			}
			else if (tempId == "2")
			{
				videoScreenFrench.addChild(txt);
				txt.multiline = true
				txt.wordWrap = true;
				txt.embedFonts = true;
				txt.defaultTextFormat = new TextFormat("Ubuntu" ,14,null,null,null,null,null,null, "center");
				txt.text = "No Camera Detected.";
				txt.width = 380;
				txt.height = txt.textHeight + 5;
				txt.x = (800 - txt.width) / 2
				txt.y = (400 - txt.textHeight) / 2;
			}
			else if (tempId == "3")
			{
				videoScreenRussian.addChild(txt);
				txt.multiline = true
				txt.wordWrap = true;
				txt.embedFonts = true;
				txt.defaultTextFormat = new TextFormat("Ubuntu" ,14,null,null,null,null,null,null, "center");
				txt.text = "No Camera Detected.";
				txt.width = 380;
				txt.height = txt.textHeight + 5;
				txt.x = (800 - txt.width) / 2
				txt.y = (400 - txt.textHeight) / 2;
			}
			else if (tempId == "4")
			{
				videoScreenSpanish.addChild(txt);
				txt.multiline = true
				txt.wordWrap = true;
				txt.embedFonts = true;
				txt.defaultTextFormat = new TextFormat("Ubuntu" ,14,null,null,null,null,null,null, "center");
				txt.text = "No Camera Detected.";
				txt.width = 380;
				txt.height = txt.textHeight + 5;
				txt.x = (800 - txt.width) / 2
				txt.y = (400 - txt.textHeight) / 2;
			}
			else
			{
				this.addChild(txt);
				txt.multiline = true
				txt.wordWrap = true;
				txt.embedFonts = true;
				txt.defaultTextFormat = new TextFormat("Ubuntu" ,14,null,null,null,null,null,null, "center");
				txt.text = "No Camera Detected.";
				txt.width = 380;
				txt.height = txt.textHeight + 5;
				txt.x = (800 - txt.width) / 2
				txt.y = (600 - txt.textHeight) / 2;
			}
			
		}
	}
}